<template>
  <VDialog @close="handleClose" :loading="loading" width="80%" :disabled="true">
    <template #content>
      <VPage class="fms-account-details">
        <VTable ref="tableRef" v-bind="tableOptins">
          <template #form="{ form }">
            <VSelects
              v-model="form.nation"
              placeholder="国家"
              :dataSourse="optionsDataAll.country"
              class="w-50"
              valueField="label"
            />
            <el-input
              v-model.trim="form.name"
              placeholder="子账号"
              clearable
              class="w-50"
            />
            <VSelectPlus
              v-model="form.platformId"
              configType="platform"
              placeholder="平台"
              class="w-50"
              valueField="platform_id"
              labelField="platform_name"
              @change="(val) => handlePlatformChange(val, form)"
            />
            <VSelects
              v-model="form.shopIds"
              :dataSourse="dict.shopData"
              class="w-50"
              valueField="shop_id"
              labelField="shop_name"
              placeholder="店铺"
              multiple
              collapse-tags
              collapse-tags-tooltip
              :isSelectAll="true"
            />
            <VSelects
              v-model="form.isBind"
              placeholder="是否绑定店铺"
              clearable
              type="isBind"
              class="w-50"
            />
          </template>
          <template #toolbar_btns>
            <VActionBar :actions="actions" />
          </template>
        </VTable>
        <Add
          v-model="addVisible"
          :title="addTitle"
          :data="addData"
          :options="optionsDataAll"
          @refresh="refresh"
          @close="addData = ''"
        />
        <Bank
          v-model="bankVisible"
          :title="bankTitle"
          @refresh="refresh"
          @close="bankDate = ''"
          :data="bankDate"
        />
      </VPage>
    </template>
  </VDialog>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import { getCountry } from "@/api/public.js";
import { getSubAccountList, stateSubAccount } from "./api.js";
import { getShop } from "@/api/index.js";
import { useEnumSelect } from "@/hooks/index.js";
import Add from "./add/index.vue";
import Bank from "./bank/index.vue";
import { baseAuthList } from "@/Auth/base.js";
const { proxy } = getCurrentInstance();
const { options: optionsData } = useEnumSelect({
  params: ["account_channel_type", "account_api_channel_type", "state"],
});
const props = defineProps({
  id: { type: [String, Number], default: null },
  accountId: { type: [String, Number], default: null },
});
watch(
  () => props.id,
  (val) => {
    if (!val) return;
    tableRef.value?.commitProxy?.("query");
  }
);
const dict = reactive({
  shopList: [],
  shopData: [],
  PlatformList: [],
});
const optionsData1 = reactive({
  //国家
  country: [],
});
const optionsDataAll = computed(() => {
  return Object.assign({}, optionsData.value, optionsData1);
});
onMounted(async () => {
  getCountryList();
  const { data } = await getShop();
  dict.shopList = data;
});
const getCountryList = async () => {
  optionsData1.country = [];

  try {
    const { code, data } = await getCountry();
    if (code !== 200) return;
    optionsData1.country = data || [];
  } catch (error) {
    console.error(error);
  }
};
const loading = ref(false);
const emit = defineEmits(["update:modelValue", "close", "refresh"]);
const tableRef = ref();
const tableOptins = reactive({
  height: "500",
  formConfig: {
    data: {},
  },
  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  columns: [
    {
      type: "checkbox",
      width: 50,
      fixed: "left",
    },
    {
      title: "ID",
      field: "id",
      width: 180,
    },
    {
      title: "子账号",
      field: "name",
      width: 180,
    },
    {
      title: "国家",
      field: "nation",
      width: 100,
    },
    {
      title: "币别",
      field: "currency",
      minWidth: 100,
    },
    {
      title: "币种总余额(API同步)",
      field: "apiBalance",
      width: 100,
    },
    {
      title: "币种总余额(流水计算)",
      field: "balance",
      width: 100,
    },
    {
      title: "账户持有人姓名",
      field: "cardholdersName",
      width: 150,
    },
    {
      title: "银行名称",
      field: "bankName",
      width: 100,
    },
    {
      title: "银行代码(路由ABA)",
      field: "bankCode",
      width: 90,
    },
    {
      title: "银行国家",
      field: "bankNation",
      width: 100,
    },
    {
      title: "银行证明",
      width: 100,
      slots: {
        default: ({ row }) => {
          return (
            <el-button type="primary" link onClick={() => handleBank(row, 1)}>
              查看
            </el-button>
          );
        },
      },
    },
    {
      title: "状态",
      field: "state",
      slots: {
        default: ({ row }) => {
          return <statusRender code={row.state} />;
        },
      },
      width: 100,
    },
    {
      title: "绑定店铺",
      field: "shop",
      width: 170,
    },
    {
      title: "操作",
      width: 120,
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {[baseAuthList.account.sub_edit] ? (
                <el-button type="primary" link onClick={() => handleAdd(row)}>
                  编辑
                </el-button>
              ) : (
                ""
              )}
              {[baseAuthList.account.sub_bank] ? (
                <el-button
                  type="primary"
                  link
                  onClick={() => handleBank(row, 2)}
                >
                  银行证明
                </el-button>
              ) : (
                ""
              )}
            </div>
          );
        },
      },
    },
  ],
  proxyConfig: {
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => {
        const { id = "", accountId = "" } = props || {};
        let params = {
          ...form,
          ...page,
          accountId,
          accountChannelId: id,
        };
        return getSubAccountList(params).then((res) => {
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});
const addVisible = ref(false);
const addData = ref(null);
const addTitle = ref("新增");
const handleAdd = (row) => {
  addVisible.value = true;
  let data = null;

  if (row?.id) {
    data = {
      ...row,
      state: row?.state?.value || null,
    };
  }
  let form = {
    ...data,
    accountId: props.accountId,
    accountChannelId: props.id,
  };
  addData.value = form || null;
  addTitle.value = data?.id ? "编辑" : "新增";
};
const bankVisible = ref(false);
const bankDate = ref(null);
const bankTitle = ref("银行证明");
const handleBank = (row, ind) => {
  bankVisible.value = true;
  bankDate.value = {
    accountSubsetId: row.id.toString(),
    id: row?.bankProveId?.toString() || null,
    ind,
  };
};
const handelStatus = (name, en) => {
  let records = tableRef.value?.$table.getCheckboxRecords();
  if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  const ids = records.map((item) => item.id);
  const handle = {
    enable: async () => {
      const { code, message } = await stateSubAccount({ ids, state: 1 });
      if (code !== 200) return;
      ElMessage.success("启用成功!");
      refresh();
    },
    disabled: async () => {
      try {
        const { code, message } = await stateSubAccount({ ids, state: 0 });
        if (code !== 200) return;
        ElMessage.success("禁用成功!");
        refresh();
      } catch (error) {}
    },
  };
  // handle[name]();
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认{en}
        <span class="text-[#3366F1] px-[4px]">{ids.length || 1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          await handle[name]();
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
        }
      } else {
        done();
      }
    },
  });
};
const handlePlatformChange = (val, form) => {
  form.shopIds = [];
  if (!val) return (dict.shopData = []);
  const shopData = dict?.shopList?.filter((item) => item.platform_id === val);
  dict.shopData = shopData;
};
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
const actions = [
  {
    label: "新增",
    type: "primary",
    icon: "add1",
    fn: () => handleAdd(null),
    permission: [baseAuthList.account.sub_add],
  },
  {
    label: "启用",
    icon: "state_enable",
    iconStyle: {
      color: "var(--main-color)",
    },
    fn: () => handelStatus("enable", "启用"),
    permission: [baseAuthList.account.sub_enable],
  },
  {
    label: "禁用",
    icon: "state_disabled",
    iconStyle: {
      color: "var(--info-color)",
    },
    fn: () => handelStatus("disabled", "禁用"),
    permission: [baseAuthList.account.sub_disabled],
  },
];
const handleClose = async (refresh) => {
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
</script>
<style lang="scss">
  .fms-account-details{
    .v-page__body{
      .vx-table__form-content{
        background-color: var(--base-dialog-bg-color) !important;
      }
    }
    .vx-table{
      .vxe-toolbar{
        background-color: var(--base-dialog-bg-color) !important;
      }
    }
    .v-pagination-container{
      background-color: var(--base-dialog-bg-color) !important;
    }
  }


</style>
